package org.example.product.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.example.core.utils.PageUtils;
import org.example.core.utils.R;
import org.example.product.dao.BrandDao;
import org.example.product.entity.BrandEntity;
import org.example.product.service.BrandCategoryService;
import org.example.product.service.BrandService;
import org.example.product.service.SpuInfoService;
import org.example.product.vo.BrandVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 小杰_cc
 * @version 1.0
 */
@Service("brandService")
public class BrandServiceImpl implements BrandService {

    @Autowired
    private BrandDao brandDao;
    @Autowired
    private BrandCategoryService brandCategoryService;
    @Autowired
    private SpuInfoService spuInfoService;

    // 查询品牌集合
    @Override
    public PageUtils queryBrandList(Integer pageNum, Integer pageSize, String name, String firstLetter) {
        // 分页
        PageHelper.startPage(pageNum,pageSize);
        // 查询
        List<BrandVo> vos = brandDao.getBrandList(name, firstLetter);
        return new PageUtils(new PageInfo<>(vos));
    }

    // 获取单个品牌信息
    @Override
    public BrandEntity queryBrandInfoById(Long id) {
        return brandDao.getBrandInfoById(id);
    }

    // 保存品牌信息
    @Override
    public int saveBrandInfo(BrandEntity brandEntity) {
        return brandDao.addBrandInfo(brandEntity);
    }

    // 修改品牌信息
    @Override
    public int editBrandInfo(BrandEntity brandEntity) {
        return brandDao.updateBrandInfo(brandEntity);
    }

    @Override
    @Transactional
    public R<?> deletes(List<Long> ids) {
        // 判断是否关联了商品
        if (spuInfoService.isSpuByBrandIds(ids)){
            return R.error("此品牌关联了商品不能删除");
        }
        // 删除关联的分类
        brandCategoryService.deleteByBrandIds(ids);
        // 删除品牌
        return brandDao.deletes(ids)>0? R.ok():R.error();
    }
}